<?php
//Start session (Already Started in App-Top
//session_start();
require_once('FEFunctions.php');

//Check whether the session variable SESS_USER_EMAIL_FE_ID is present or not
if (!isset($_SESSION['SESS_USER_EMAIL_FE_ID'])) {
    if (isset($_SESSION['SESS_USER_PAID_FE_ID'])) { unset($_SESSION['SESS_USER_PAID_FE_ID']); }
    if (isset($_SESSION['SESS_USER_FNAME_FE_ID'])) { unset($_SESSION['SESS_USER_FNAME_FE_ID']); }

    // Check for Cookie
    if (isset($_COOKIE['wog_cookie_SESS_USER_EMAIL_FE_ID']))
    {
        require_once('config.inc.php');
        require_once(MYSQL);
        require_once(STATEM_MYSQL);

        $emailRecover = heal($_COOKIE['wog_cookie_SESS_USER_EMAIL_FE_ID']);
        $emailRecover = clean($emailRecover, $dbc);

        if (isValid('email', $emailRecover))
        {
            //// Check for the existence of that email address in Cookie
            $q = sprintf($Q_NamePaid_Email_AuthorizeCookie, $emailRecover);
            $r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

            if (mysqli_num_rows($r) == 1)
            {
                //Cookie info correct
                session_regenerate_id();
                $member = mysqli_fetch_array ($r, MYSQLI_ASSOC);
                $_SESSION['SESS_USER_EMAIL_FE_ID'] = $emailRecover;
                $_SESSION['SESS_USER_PAID_FE_ID'] = $member['Paid'];
                $_SESSION['SESS_USER_FNAME_FE_ID'] = $member['FirstName'];

                //Free Result and DB
                mysqli_free_result($r);
                mysqli_close($dbc);

            }
            else
            {
                //// Info Cookie Incorrect
                setcookie('wog_cookie_SESS_USER_EMAIL_FE_ID', '' , 0);
                mysqli_free_result($r);
                mysqli_close($dbc);
                header("Location: index.php");
                exit();
            }
        }
        else
        {
            //// Info Cookie Incorrect
            setcookie('wog_cookie_SESS_USER_EMAIL_FE_ID', '' , 0);
            header("Location: index.php");
            exit();
        }
    }
    else
    {
        header("Location: index.php");
        exit();
    }
}

//Check whether the session variable SESS_USER_EMAIL_FE_ID is present or not
if (!isValid('email', $_SESSION['SESS_USER_EMAIL_FE_ID'])) {
    if (isset($_SESSION['SESS_USER_EMAIL_FE_ID'])) { unset($_SESSION['SESS_USER_EMAIL_FE_ID']); }
    if (isset($_SESSION['SESS_USER_PAID_FE_ID'])) { unset($_SESSION['SESS_USER_PAID_FE_ID']); }
    if (isset($_SESSION['SESS_USER_FNAME_FE_ID'])) { unset($_SESSION['SESS_USER_FNAME_FE_ID']); }

    header("Location: index.php");
    exit();
}

//// TODO: Update the Paid Status since it might change! (Authorizer)

// Front End
?>